package www.nfin.ya.super_filter_chain;

import www.nfin.ya.entity.excel.CellEntity;
import www.nfin.ya.entity.excel.RowEntity;
import www.nfin.ya.service.SystemContextServer;


import java.util.*;
import java.util.regex.Pattern;

public class StartupNote{


    public boolean executeFilter(List<RowEntity> rows){
        CommentFilter commentFilter = new CommentFilter(new ValueFilter(null));
        Map<String,Map> columnMap = getColumnMap();

        for (int i = 0; i < rows.get(0).getCells().size(); i++) {
            Map rules = getRules(rows.get(0).getCells().get(i), columnMap);
            if(rules != null){
                for (int j = 0; j < rows.size(); j++) {
                    commentFilter.execute(rows.get(j).getCells().get(i),rules);
                }
            }
        }

//        yamlProperties.get("s");
        return true;
    }

    private Map getRules(CellEntity cellEntity, Map<String,Map> columnMap){
        String tableName = cellEntity.getTableName();
        String columnName = cellEntity.getColumnName();
        //当 使用别名时，tableName为null
        if(null == tableName ){
            tableName = "null";
        }
        for (String tableColumn : columnMap.keySet()) {
            String[] split = tableColumn.split(":");
            if(Pattern.matches(split[0],tableName)){
                if(Pattern.matches(split[1],columnName)){
                    return columnMap.get(tableColumn);
                }
            }
        }
        return null;
    }
    private ArrayList<LinkedHashMap> getTablesMap() {
        //������
        Map yamlProperties = SystemContextServer.getYamlProperties("superman.yaml",Map.class);
        ArrayList<LinkedHashMap> tableList = (ArrayList<LinkedHashMap>) ((Map)yamlProperties.get("superman")).get("tablesMap");
        tableList.sort((x,y) ->{
            return (int)x.get("order") - (int)y.get("order");
        });
        for (LinkedHashMap linkedHashMap : tableList) {
            linkedHashMap.put("tableName",((String)linkedHashMap.get("tableName")).toLowerCase());
            for (LinkedHashMap columnMap : (ArrayList<LinkedHashMap>) linkedHashMap.getOrDefault("field", new ArrayList<>())) {
                columnMap.put("fieldName",((String)columnMap.get("fieldName")).toLowerCase());
            }
        }
        return tableList;
    }
    private Map<String,Map> getColumnMap() {
        ArrayList<LinkedHashMap> tablesMap = getTablesMap();
        LinkedHashMap<String,Map> result = new LinkedHashMap<>();

        for (LinkedHashMap tablePerp : tablesMap) {
            ArrayList<LinkedHashMap> columnMap = (ArrayList<LinkedHashMap>)tablePerp.getOrDefault("field",new LinkedHashMap<>());
            for (LinkedHashMap columnPerp : columnMap) {
                result.put(tablePerp.get("tableName")+":"+columnPerp.get("fieldName"),columnPerp);
            }
        }



        return result;

    }
}
